package com.xunua.webrtcdemo.utils;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;


public class JsonUtil {

    private static Gson gson = null;

    public static Gson getInstance() {
        if (gson == null) {
            gson = new Gson();
            synchronized (Object.class) {
                if (gson != null) {
                    return gson;
                }
            }
        } else {
            return gson;
        }
        return null;
    }

    private JsonUtil() {
    }

    /**
     * 将object对象转成json字符串
     */
    public static String obj2json(Object object) {
        String gsonString = null;
        if (getInstance() != null) {
            gsonString = getInstance().toJson(object);
        }
        return gsonString;
    }

    /**
     * 将object对象转成json字符串
     */
    public static String obj2jsonNull(Object object) {
        String gsonString = null;
        Gson gsonNull = new GsonBuilder().serializeNulls().create();
        gsonString = gsonNull.toJson(object);
        return gsonString;
    }


    /**
     * 将gsonString转成泛型bean
     */
    public static <T> T json2pojo(String gsonString, Class<T> cls) {
        T t = null;
        if (getInstance() != null) {
            t = getInstance().fromJson(gsonString, cls);
        }
        return t;
    }

    /**
     * 转成list
     */
    public static <T> ArrayList<T> json2beans(String json, Class<T> cls) {
        ArrayList<T> list = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(getInstance().fromJson(elem, cls));
        }
        return list;
    }


}
